<template>
    <div class="editPages-content">
        <div class="editPages-title-content desktop-only">
            <div class="left-title">
                <div class="left-tag"></div>
                <span>编辑信息</span>
            </div>
            <div class="right-btns">
                <el-button type="primary" @click="submitForm(ruleFormRef)" id="admin-task-update-submit">提交</el-button>
                <el-button @click="resetForm(ruleFormRef)" id="admin-task-update-close">关闭</el-button>
            </div>
        </div>

        <div class="mobile-btns mobile-only">
            <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
            <el-button @click="resetForm(ruleFormRef)">关闭</el-button>
        </div>

        <el-form ref="ruleFormRef" style="max-width: 600px;margin: 0 auto;margin-top: 30px;" :model="ruleForm"
            :rules="rules" label-width="auto" class="demo-ruleForm" :size="formSize" status-icon>
            <el-form-item label="任务名称" prop="title" id="admin-task-update-input-title">
                <el-input v-model="ruleForm.title" clearable id="admin-task-update-input-title" disabled />
            </el-form-item>
            <el-form-item label="任务内容" prop="content" id="admin-task-update-input-content">
                <el-input v-model="ruleForm.content" type="textarea" clearable id="admin-task-update-input-content" />
            </el-form-item>
            <el-form-item label="执行人" prop="createName" id="admin-task-update-input-userId" disabled>
                <el-input v-model="ruleForm.createName" clearable id="admin-task-update-input-userId" />
            </el-form-item>
            <el-form-item label="任务状态" id="admin-task-update-radio-workStatusId">
                <el-radio-group v-model="ruleForm.workStatusId" id="admin-task-update-radio-workStatusId">
                    <el-radio :value="1">已完成</el-radio>
                    <el-radio :value="0">进行中</el-radio>
                    <el-radio :value="2">已到期</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="截止时间" id="admin-task-update-radio-endTime">
                <el-date-picker v-model="ruleForm.endTime" type="date" placeholder="请选择截止日期" style="width: 100%"
                    value-format="YYYY-MM-DD hh:mm:ss" format="YYYY-MM-DD hh:mm:ss"
                    id="admin-task-update-radio-endTime" />
            </el-form-item>
            <el-form-item label="附件：" id="admin-task-update-radio-file">
                <!-- <input type="file" accept=".doc,.docx" style="margin-bottom: 10px;"  id="admin-task-update-radio-file"/> -->
                <el-upload ref="upload" class="upload-demo" :before-upload="upload" :before-remove="removeFile"
                    :limit="1" id="admin-task-update-radio-file">
                    <template #trigger>
                        <el-button type="primary" plain id="admin-task-update-radio-file">
                            <el-icon style="font-size: 25px;margin-right: 15px;">
                                <UploadFilled />
                            </el-icon>上传
                        </el-button>
                    </template>

                </el-upload>


                <div v-if="ruleForm.file" class="file-display">
                    <el-icon>
                        <Document />
                    </el-icon>
                    <span class="file-name">{{ ruleForm.file.name }}</span>
                    <el-icon class="delete-icon" @click="removeFile">
                        <Delete />
                    </el-icon>
                </div>
                <div>
                    <samp style="font-size: 15px; color:#888;">支持doc/docx格式附件,附件大小不能超过4M</samp>
                </div>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router"
import { UploadFilled, Document, Delete } from '@element-plus/icons-vue'
import { updateTask } from '@/api/index.js';
import { ElMessage, dayjs } from 'element-plus'

const router = useRouter();
const route = useRoute();
const tasks = JSON.parse(route.query.tasks)
console.log('接收到的数据:', tasks)

const formSize = ref('default')
const ruleFormRef = ref()
const ruleForm = ref({
    id: '',
    title: '',
    content: '',
    createName:'',
    userId: '',
    workStatusId: 0,
    endTime: '',
    updateTime: '',
    require: '',
    attachmentId: '',
    file: null
})
const ee = ref('')


onMounted(() => {
    ruleForm.value = {
        id: tasks.id || '',
        title: tasks.title || '',
        content: tasks.content || '',
        createName:tasks.createName || '',
        userId: tasks.userId || '',
        workStatusId: Number(tasks.workStatusId || 0),
        endTime: dayjs(tasks.endTime * 1).format("YYYY-MM-DD hh:mm:ss") || '',
        updateTime: tasks.updateTime || '',
        require: tasks.require || '',
        attachmentId: tasks.attachmentId || '',
        file: tasks.file || null
    }
    ee.value = tasks.endTime
    console.log('表单数据:', ruleForm.value)
})

const rules = reactive({
    title: [
        { required: true, message: '请输入任务名称', trigger: 'blur' },
    ],
    content: [
        { required: true, message: '请输入任务内容', trigger: 'blur' },
    ],
    createName: [
        { required: true, message: '请输入创建人', trigger: 'blur' },
    ]
})

// 文件列表
const fileList = ref([])

// 处理文件选择
const handleFileChange = (event) => {
    console.log(event);

    const file = event.target.files[0]
    if (!file) return

    console.log('选择的文件:', file)

    // 检查文件类型
    const isDoc = file.type === 'application/msword' ||
        file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    if (!isDoc) {
        ElMessage.error('只能上传 DOC/DOCX 格式的文件!')
        event.target.value = '' // 清空选择
        return
    }

    // 检查文件大小（4MB = 4 * 1024 * 1024 bytes）
    const isLt4M = file.size / 1024 / 1024 < 4
    if (!isLt4M) {
        ElMessage.error('文件大小不能超过 4MB!')
        event.target.value = '' // 清空选择
        return
    }

    // 读取文件内容
    const reader = new FileReader()

    reader.onload = (e) => {
        try {
            // 获取文件的二进制数据
            const binaryData = new Uint8Array(e.target.result)
            console.log('文件二进制数据:', binaryData)

            // 存储二进制数据到 file
            ruleForm.value.file = e.target.result
            // 存储文件名到 attachmentId
            // ruleForm.value.attachmentId = file.name

            ElMessage.success('文件已选择')
        } catch (error) {
            console.error('文件处理错误:', error)
            ElMessage.error('文件处理失败')
        }
    }

    reader.onerror = (error) => {
        console.error('文件读取错误:', error)
        ElMessage.error('文件读取失败')
    }

    // 以二进制格式读取文件
    reader.readAsArrayBuffer(file)
}

const upload = (file) => {
    console.log(file);

    ruleForm.value.file = file;

}
const upload2 = (file) => {

    ruleForm.value.file = file;

}



// 提交
const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            // if (ruleForm.value.attachmentId == null || ruleForm.value.attachmentId == '') {
            //     delete ruleForm.value.attachmentId
            // }
            // if (ruleForm.value.file == null || ruleForm.value.file == '') {
            //     delete ruleForm.value.file
            // }
            const updateAdminWorkParam = { ...ruleForm.value, endTime: ee.value, updateTime: Date.now().toString() }
            console.log(updateAdminWorkParam);

            updateTask(updateAdminWorkParam).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success('提交成功')
                    router.go(-1)
                } else {
                    ElMessage.error('提交失败')
                }
            })
        } else {
            console.log('error submit!', fields)
            ElMessage.error('请填写必填项')
        }
    })
}

const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
    router.go(-1)

}

// 添加删除文件方法
const removeFile = () => {
    ruleForm.value.file = null;
    ruleForm.value.attachmentId = '';
    ElMessage.success('文件已移除');
}

</script>

<style lang="less" scoped>
@media screen and (max-width: 768px) {
    .desktop-only {
        display: none !important;
    }
}

@media screen and (min-width: 769px) {
    .mobile-only {
        display: none !important;
    }
}

.mobile-btns {
    display: flex;
    justify-content: space-around;
    padding: 10px;

    .el-button {
        flex: 1;
        margin: 0 5px;
    }
}

.editPages-title-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.left-title {
    display: flex;
    align-items: center;
}

.left-tag {
    background: #409EFF;
    margin-right: 10px;
    height: 20px;
    width: 7px;
    border-radius: 10px;
}

.file-display {
    margin-top: 10px;
    padding: 8px 12px;
    background-color: #f4f4f5;
    border-radius: 4px;
    display: flex;
    align-items: center;
    gap: 8px;
}

.file-name {
    color: #606266;
    font-size: 14px;
}

.delete-icon {
    margin-left: auto;
    color: #909399;
    cursor: pointer;

    &:hover {
        color: #f56c6c;
    }
}
</style>